// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成
package com.fowo.api.exportCenter.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.IdListPo;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.R;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.exportCenter.model.ExportCenterImportPo;
import com.fowo.api.exportCenter.model.ExportCenterItemVo;
import com.fowo.api.exportCenter.model.ExportCenterSearchParamPo;
import com.fowo.api.exportCenter.model.ExportCenterVo;
import com.fowo.api.exportCenter.service.ExportCenterService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StreamUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Tag(name = "导出中心")
@RequestMapping("/api/export-center")
@RestController
public class ExportCenterController {

  @Resource
  private ExportCenterService service;


  @Operation(summary = "查询结果")
  @GetMapping
  public R<List<ExportCenterItemVo>> search(ExportCenterSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    return R.data(service.search(search));
  }

  @Operation(summary = "查询最后更新时间")
  @GetMapping("lastUpdateTime")
  public R<Date> searchLastUpdateTime(ExportCenterSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    return R.data(service.searchLastUpdateTime(search));
  }

  @Operation(summary = "获取分页查询结果")
  @GetMapping("page")
  public R<Page<ExportCenterItemVo>> getPage(ExportCenterSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    return R.data(service.pageSearch(search));
  }

  @Operation(summary = "获取当前用户的分页查询结果")
  @GetMapping("my-page")
  public R<Page<ExportCenterItemVo>> getMyPage(ExportCenterSearchParamPo search) {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    if (jwtUserInfo == null) {
      return R.fail("此操作需要登录");
    }
    search.setDisableDataPremissions(true);
    search.setCreateUserEq(jwtUserInfo.getUserId());
    return R.data(service.pageSearch(search));
  }

  @Operation(summary = "获取详情")
  @GetMapping("{id}")
  public R<ExportCenterVo> getVoById(@PathVariable Long id) {
    return R.data(() -> service.getVoById(id));
  }

  @Operation(summary = "获取编号相关的导出名称列表")
  @GetMapping("name/{ids}")
  public R<List<String>> getVoById(@PathVariable String ids) {
    List<Long> idList = Arrays
      .asList(ids.split(","))
      .stream()
      .map(Long::valueOf)
      .collect(Collectors.toList());
    return R.data(() -> service.getNameByIds(idList));
  }

  @PreAuthorize("@am.canAccess('exportCenterCreate')")
  @Operation(summary = "新增")
  @PostMapping
  public R<Long> create(@Validated @RequestBody ExportCenterVo model) {
    return R.data(() -> service.create(model));
  }

  @PreAuthorize("@am.canAccess('exportCenterEdit')")
  @Operation(summary = "更新")
  @PutMapping
  public R update(@RequestBody ExportCenterVo model) {
    return R.run(() -> service.update(model));
  }

  @PreAuthorize("@am.canAccess('exportCenterEdit')")
  @Operation(summary = "编辑更新")
  @PutMapping("edit")
  public R updateForEdit(@RequestBody ExportCenterVo model) {
    return R.run(() -> service.updateForEdit(model));
  }

  @Operation(summary = "删除")
  @DeleteMapping("{id}")
  public R delete(@PathVariable Long id) {
    return R.run(() -> service.delete(id));
  }

  @Operation(summary = "批量删除")
  @DeleteMapping("batch")
  public R batchDelete(@RequestBody IdListPo po) {
    return R.run(() -> service.batchDelete(po.getIds()));
  }

  @PreAuthorize("@am.canAccess('exportCenterCreate')")
  @Operation(summary = "导入预览")
  @PostMapping("import-preview")
  public R<List<ImportRow<ExportCenterImportPo>>> importPreview(
    @RequestBody SysFile sysFile
  ) {
    return R.data(() -> service.importPreview(sysFile));
  }

  @PreAuthorize("@am.canAccess('exportCenterCreate')")
  @Operation(summary = "完成导入")
  @PostMapping("import-done")
  public R importDone(@RequestBody List<ImportRow<ExportCenterImportPo>> rows) {
    return R.run(() -> service.importDone(rows));
  }

  @Operation(summary = "下载导入模版")
  @GetMapping("import/template")
  public void downloadImportTemplate(HttpServletResponse response)
    throws IOException {
    ResponseUtils.setAttachmentFileName(response, "导出中心导入模版.xlsx");
    InputStream inputStream = new ClassPathResource(
      "templates/ExportCenter.xlsx"
    )
      .getInputStream();
    StreamUtils.copy(inputStream, response.getOutputStream());
  }

  @Operation(summary = "导出")
  @GetMapping("export")
  public void export(
    ExportCenterSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
    search.setCurrentUserId(jwtUserInfo.getUserId());
    service.export(search, response);
  }

//  @Operation(summary = "通用导出 异步")
//  @GetMapping("export3")
//  public R export3(
//          Map search, String code,HttpServletResponse response
//  ) throws Exception {
//    ModuleSystemEnum module = ModuleSystemEnum.valueOfCode(code);
//    if (null == module) {
//      return R.fail("当前模块尚未配置导入功能");
//    }
//    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
//    exportCommonService.export2(search,jwtUserInfo.getUserId(),module,response);
////    Thread t=new Thread(new Runnable() {
////      @SneakyThrows
////      @Override
////      public void run() {
////        exportCommonService.export2(search,jwtUserInfo.getUserId(),module,response);
////      }
////    });
////    t.start();
//    return R.success("使用异步导出成功，请稍后查询",null);
//  }
//
//  @Operation(summary = "通用导出 异步")
//  @GetMapping("export2")
//  public R export2(
//          Map search, String code
//  ) throws Exception {
//    ModuleSystemEnum module = ModuleSystemEnum.valueOfCode(code);
//    if (null == module) {
//      return R.fail("当前模块尚未配置导入功能");
//    }
//    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
//    Thread t=new Thread(new Runnable() {
//      @SneakyThrows
//      @Override
//      public void run() {
//        exportCommonService.export(search,jwtUserInfo.getUserId(),module);
//      }
//    });
//    t.start();
//    return R.success("使用异步导出成功，请稍后查询",null);
//  }
//
//  @Operation(summary = "导出列队")
//  @GetMapping("exportQueue")
//  public R exportQueue(
//          Map search, String code
//  ) throws Exception { ModuleSystemEnum module = ModuleSystemEnum.valueOfCode(code);
//    if (null == module) {
//      return R.fail("当前模块尚未配置导入功能");
//    }
//    JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();
//    ExportEntityVo exportVo=new ExportEntityVo();
//    exportVo.setSearch(search);
//    exportVo.setModule(module);
//    exportVo.setUserId(jwtUserInfo.getUserId());
//    rabbitTemplate.convertAndSend("exportCenter.exchange", "exportCenter.key", exportVo);
//    return R.success("使用列队导出成功，请稍后查询",null);
//  }
}
